import { ref, shallowRef, reactive, toRefs, nextTick, onMounted } from 'vue'
import { useAccidentTableList } from '@/store';
import * as echarts from 'echarts'
import * as DashboardApi from "@/service/api/dashboard";
import getTrendsLineChartOption from './data/line.chart.js'
import getIndicatorLineChartOption from './data/indicator-line.chart.js'


const tableList = useAccidentTableList()
/**
 * @description: 今日事故数总览
 * @return {*}
 */
function getCompareInitForm() {
  return {
    todayData: {
      "totalCount": 0, //总数
      "generalCount": 0, //一般事故数
      "simpleCount": 0//简易事故数},
    },
    yesterdayData: {
      "totalCount": 0, //总数
      "generalCount": 0, //一般事故数
      "simpleCount": 0 //简易事故数
    }
  }
}
/**
 * @description: 今日事故数总览
 * @return {*}
 */
export function useAccidentCompare() {
  const compareModel = reactive(getCompareInitForm())

  const getCompareInfo = async () => {
    resetCompareValue()
    const res = await DashboardApi.GetHomeCompareData()
    const { todayData, yesterdayData } = res || {}
    if (!todayData || !yesterdayData) return
    compareModel.todayData = todayData
    compareModel.yesterdayData = yesterdayData
  }

  function resetCompareValue() {
    const { todayData, yesterdayData } = getCompareInitForm()
    compareModel.todayData = todayData
    compareModel.yesterdayData = yesterdayData
  }
  return {
    ...toRefs(compareModel),
    getCompareInfo
  }
}



export function useAccidentIndicatorStatistics2() {
  const indicatorLineChartRef = ref(null)
  const indicatorLineChartInstance = shallowRef(null)

  let timer = 0

  async function getIndicatorLineChartData() {

    const data = await DashboardApi.GetHomeIndicatorStatistics()

    const xLabel = []
    const accidentCounts = []
    const injuryCounts = []
    const deathCounts = []
    const lossCounts = []
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      xLabel.unshift(item.name)
      accidentCounts.unshift(item.sgs)
      injuryCounts.unshift(item.ssrs)
      deathCounts.unshift(item.swrs)
      lossCounts.unshift((item.ccss / 10000).toFixed(2))
    }

    const option = getIndicatorLineChartOption({ xLabel, accidentCounts, injuryCounts, deathCounts, lossCounts })
    setChartOption(option)

    let len = 0
    clearInterval(timer)
    timer = setInterval(() => {
      if (len === xLabel.length) {
        len = 0
      }
      indicatorLineChartInstance.value.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: len,
      })
      len++
    }, 3000)
  }

  function initChart() {
    indicatorLineChartInstance.value = echarts.init(indicatorLineChartRef.value)

    indicatorLineChartInstance.value.on('click', (params) => {
      handleChartClick(params)
    })

  }
  async function handleChartClick(params) {
    if (params.seriesName === undefined) return
    // 获取图表实例的option配置
    const option = indicatorLineChartInstance.value.getOption();

    // 获取当前点击的x轴索引
    const dataIndex = params.dataIndex;

    // 构建包含所有指标的数据对象
    const allSeriesData = {};
    option.series.forEach(series => {
      allSeriesData[series.name] = series.data[dataIndex];
    });

    // 获取区域名称
    const regionName = option.xAxis[0].data[dataIndex];

    console.log('完整列数据:', {
      region: regionName,
      ...allSeriesData
    });
    let name = ''
    switch (regionName) {
      case '今日':
        name = 'today'
        break;
      case '昨日':
        name = 'yesterday'
        break;
      case '上周':
        name = 'lastWeek'
        break;
      case '上月':
        name = 'lastMonth'
        break;
      default:
        break;
    }
    let param = {
      pageNum: '1',
      pageSize: String(allSeriesData.事故数),        // 可根据需要调整
      flag: name,    // 添加区域参数
      // indicators: allSeriesData
    };
    const res = await DashboardApi.GetHomeindicatorStatisticPageInfo(param)
    tableList.accidentPageInfoList = res.rows
    tableList.accidentPageInfoShow = true
  }
  function setChartOption(option) {
    indicatorLineChartInstance.value.setOption(option)
  }

  onMounted(() => {
    initChart()
    getIndicatorLineChartData()
  })



  return {
    indicatorLineChartRef,
    indicatorLineChartInstance,
    getIndicatorLineChartData,
    handleChartClick
  }
}


/**
 * @description: 事故四项指数统计
 * @return {*}
 */
export function useAccidentIndicatorStatistics() {
  const indicatorData = ref([])
  const tableRef = ref(null)


  const getIndicatorStatistics = async () => {
    indicatorData.value = []
    const data = await DashboardApi.GetHomeIndicatorStatistics()
    indicatorData.value = data

    nextTick(initTableAutoHoverState)
  }


  let timer = 0
  /**
   * @description: 表格悬浮选中动画
   * @return {*}
   */
  function initTableAutoHoverState() {
    if (timer) return
    let trIndex = 0
    const trList = tableRef.value.querySelectorAll('.el-table__body-wrapper tbody tr')
    if (!trList.length) return
    trList[trIndex].classList.add('hover-row')
    timer = setInterval(() => {
      trList.forEach((item) => {
        item.classList.remove('hover-row')
      })

      trList[trIndex].classList.add('hover-row')

      trIndex++
      if (trIndex >= trList.length) {
        trIndex = 0
      }
    }, 5000)
  }

  function onTableMouseEnter() {
    clearInterval(timer)
    const trList = tableRef.value.querySelectorAll('.el-table__body-wrapper tbody tr')
    trList.forEach((item) => {
      item.classList.remove('hover-row')
    })
  }

  function onTableMouseLeave() {
    initTableAutoHoverState()
  }


  return {
    tableRef,
    indicatorData,
    getIndicatorStatistics,
    onTableMouseEnter,
    onTableMouseLeave,
    initTableAutoHoverState
  }
}

/**
 * @description: 事故
 * @return {*}
 */
export function useAccidentTrendsLineChart() {
  const lineChartRef = ref(null)
  const lineChartInstance = shallowRef(null)
  async function getLineChartData() {

    const data = await DashboardApi.GetHomeTrendsLineChartData()

    const { compare, current } = data || {}
    if (compare && current) {
      const option = getTrendsLineChartOption(data)
      setChartOption(option)
    }
  }

  function initChart() {
    lineChartInstance.value = echarts.init(lineChartRef.value)
  }
  function setChartOption(option) {
    lineChartInstance.value.setOption(option)
  }

  onMounted(() => {
    initChart()
    getLineChartData()
  })

  return {
    lineChartRef,
    getLineChartData,
    lineChartInstance,
  }
}
